package com.example.controller;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.StrUtil;
import com.aliyun.oss.OSSException;
import com.example.common.Result;
import com.example.common.enums.ResultCodeEnum;
import com.example.utils.AliOssUtil;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 文件接口
 */
@RestController
@RequestMapping("/files")
@Slf4j
public class FileController {

    // 文件上传存储路径
    private static final String filePath = System.getProperty("user.dir") + "/files/";

    @Value("${server.port:9090}")
    private String port;

    @Value("${ip:localhost}")
    private String ip;

    @Resource
    private AliOssUtil aliOssUtil;

    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        String flag;
        synchronized (FileController.class) {
            flag = System.currentTimeMillis() + "";
            ThreadUtil.sleep(1L);
        }
        String fileName = file.getOriginalFilename();
        try {
            if (!FileUtil.isDirectory(filePath)) {
                FileUtil.mkdir(filePath);
            }
            // 文件存储形式：时间戳-文件名
            FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);  // ***/manager/files/1697438073596-avatar.png
            System.out.println(fileName + "--上传成功");

        } catch (Exception e) {
            System.err.println(fileName + "--文件上传失败");
        }
        String http = "http://" + ip + ":" + port + "/files/";
//        try {
//            //原始文件名
//            String originalFilename = file.getOriginalFilename();
//
//            //截取原始文件名后缀 .jpg
//            String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
//            //构造新文件名
//            String objectName = UUID.randomUUID().toString() + extension;
//
//            String filePath = aliOssUtil.upload(file.getBytes(), objectName);
//            log.info("文件上传成功！");
//            return Result.success(filePath);
//        } catch (IOException e) {
//            log.error("文件上传失败：{}",e);
//        }
//
//        return Result.error(ResultCodeEnum.UPLOAD_ERROR);
        return Result.success(http + flag + "-" + fileName);  //  http://localhost:9090/files/1697438073596-avatar.png
    }


    /**
     * 获取文件
     *
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")   //  1697438073596-avatar.png
    public void avatarPath(@PathVariable String flag, HttpServletResponse response) {



        OutputStream os;
        try {
            if (StrUtil.isNotEmpty(flag)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(flag, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(filePath + flag);
                os = response.getOutputStream();
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            System.out.println("文件下载失败");
        }
    }


    /*@GetMapping("/download")
    public void download(String objectName, HttpServletResponse response) throws IOException {
        try {
            // 生成带有过期时间的 URL，有效期为 3600 秒
            Date expiration = new Date(2694655614L);
            URL url = ossClient.generatePresignedUrl(bucketName, objectName, expiration);
            // 将 URL 设置为另存为链接
            String downloadUrl = url.toString() + "&download=" + URLEncoder.encode(objectName, "UTF-8");
            // 设置 Content-Disposition 响应头
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(objectName, "UTF-8"));
            // 将用户重定向到另存为链接
            response.sendRedirect(downloadUrl);
            System.out.println("Object " + objectName + " was downloaded successfully.");
        } catch (OSSException oe) {
            System.out.println("Error downloading object " + objectName + ": " + oe.getMessage());
        }
    }*/



    /**
     * 删除文件
     *
     * @param flag
     */
    @DeleteMapping("/{flag}")
    public void delFile(@PathVariable String flag) {
        FileUtil.del(filePath + flag);
        System.out.println("删除文件" + flag + "成功");
    }


}
